import { tenant } from "../../api";
import Vue from "vue";
const MUTATION_TYPES = {
  SEARCH: "SEARCH",
  TENANT: "TENANT",
  TENANTINFO: "TENANTINFO",
};

const state = {
  tenantList: [],
  lastTenant: {},
  tenantInfo: {}
};
const getters = {};

const mutations = {
  [MUTATION_TYPES.SEARCH] (state, tenantList) {
    state.tenantList = tenantList;
  },
  [MUTATION_TYPES.TENANT] (state, tenant) {
    Vue.writeStorage("TENANT:" + tenant.tenantId, tenant, 300);
    state.lastTenant = tenant;
  },
  [MUTATION_TYPES.TENANTINFO] (state, tenantInfo) {
    state.tenantInfo = tenantInfo
  },
};

const actions = {
  async search ({ commit }, filter) {
    let tenantList = await tenant.search(filter);
    commit(MUTATION_TYPES.SEARCH, tenantList);
    tenantList?.forEach((tenant) => commit(MUTATION_TYPES.TENANT, tenant));
    return tenantList;
  },
  async getTenantById ({ commit }, tenantId) {
    let tenant = await tenant.getTenantById(tenantId);
    commit(MUTATION_TYPES.TENANT, tenant);
    return tenant;
  }
};

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
};
